package ee.wm.ilmataat.xml;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.Context;
import ee.wm.ilmataat.Location;
import ee.wm.ilmataat.Station;
import ee.wm.ilmataat.R.raw;

public class WeatherXmlImporter {

	private static final String EMHI_OBSERVATIONS_XML_URL = "http://www.emhi.ee/ilma_andmed/xml/observations.php";

	public List<Station> importStations(Context context) {
		List<Station> stations = new ArrayList<Station>();
		try {
			SAXParserFactory parserFactory = SAXParserFactory.newInstance();
			SAXParser parser = parserFactory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();

			URL sourceUrl = new URL(EMHI_OBSERVATIONS_XML_URL);

			StationsXmlHandler xmlHandler = new StationsXmlHandler();
			xmlReader.setContentHandler(xmlHandler);
			InputSource inputSource = new InputSource(sourceUrl.openStream());
			inputSource.setEncoding("iso-8859-1");
			xmlReader.parse(inputSource);
			stations = xmlHandler.getStations();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		}

		fillStationsLocation(context, stations);
		return stations;
	}

	private void fillStationsLocation(Context context, List<Station> stations) {
		Map<String, Location> locations = importLocationsFromRawXml(context);
		for (Station station : stations) {
			station.setLocation(locations.get(station.getName()));
		}
	}

	private Map<String, Location> importLocationsFromRawXml(Context context) {
		Map<String, Location> locations = new HashMap<String, Location>();
		try {
			SAXParserFactory parserFactory = SAXParserFactory.newInstance();
			SAXParser parser = parserFactory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();

			InputStream ins = context.getResources().openRawResource(
					raw.coordinates);
			CoordinatesXmlHandler xmlHandler = new CoordinatesXmlHandler();
			xmlReader.setContentHandler(xmlHandler);
			InputSource inputSource = new InputSource(ins);
			inputSource.setEncoding("iso-8859-1");
			xmlReader.parse(inputSource);
			locations = xmlHandler.getLocations();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		}

		return locations;
	}

}
